import hmac
import hashlib

def generate_mqtt_credentials(deviceId, productKey, deviceKey, deviceSecret,
                              signMethod="0", authType="0", operator="0"):
    """
    生成 MQTT ClientId、Username、Password
    
    参数:
        deviceId    : 设备ID (ICCID 或 SN/MAC，取决于 operator)
        productKey  : 产品Key
        deviceKey   : 设备Key
        deviceSecret: 设备密钥
        signMethod  : 加密算法 (0=hmac_sha256, 1=SM3)
        authType    : 认证方式 (一机一密=0)
        operator    : 运营商 (0=非蜂窝, 1=联通, 2=移动, 3=电信, 4=广电)
    """

    # 1. 生成 ClientId
    mqttClientId = f"{deviceId}|{productKey}|{signMethod}|{authType}|{operator}"

    # 2. 生成 Username
    mqttUsername = f"{deviceKey}|{productKey}"

    # 3. 拼接参数: deviceId + deviceKey + productKey
    concat_str = f"{deviceId}{deviceKey}{productKey}"

    # 4. 生成 Password
    if signMethod == "0":  # hmac_sha256
        signature = hmac.new(
            deviceSecret.encode("utf-8"),
            concat_str.encode("utf-8"),
            hashlib.sha256
        ).hexdigest()
        mqttPassword = signature
    elif signMethod == "1":  # SM3 算法（此处需要 SM3 库支持）
        raise NotImplementedError("SM3 算法暂未实现")
    else:
        raise ValueError("Unsupported signMethod")

    return mqttClientId, mqttUsername, mqttPassword


if __name__ == "__main__":
    # 示例参数（你需要替换 deviceId）
    productKey = "cu1cefqr73hy9q5F"
    deviceKey = "Ndikyud5WLgpywD"
    deviceSecret = "BA88A82BAD680F5089D1663960F8BC62"
    deviceId = "SN1234567890"   # 请替换为你的 SN/MAC 或 ICCID

    clientId, username, password = generate_mqtt_credentials(
        deviceId=deviceId,
        productKey=productKey,
        deviceKey=deviceKey,
        deviceSecret=deviceSecret,
        signMethod="0",   # hmac_sha256
        authType="0",
        operator="0"      # 非蜂窝网络
    )

    print("mqttClientId:", clientId)
    print("mqttUsername:", username)
    print("mqttPassword:", password)
